import { configureStore, combineReducers } from "@reduxjs/toolkit";
import { persistStore, persistReducer } from "redux-persist";
import { TypedUseSelectorHook, useDispatch as useReduxDispatch, useSelector as useReduxSelector } from "react-redux";
import storage from "redux-persist/lib/storage";
import { thunk } from "redux-thunk";
import reduxPromise from "redux-promise";
import global from "./modules/global";
import menu from "./modules/menu";
import tabs from "./modules/tabs";
import auth from "./modules/authorization/authorization";
import breadcrumb from "./modules/breadcrumb";
import applayout from "./modules/applayout/index";
// create reducer
const reducer = combineReducers({
	global,
	menu,
	tabs,
	auth,
	applayout,
	breadcrumb
});

// redux persist
const persistConfig = {
	key: "redux-state",
	storage: storage
};
const persistReducerConfig = persistReducer(persistConfig, reducer);

// redux middleWares
// const middleWares = [thunk, reduxPromise];
// 创建一个回调函数，接收 getDefaultMiddleware，并返回中间件数组
const customMiddleware = (getDefaultMiddleware: () => any) => {
	// 添加你需要的中间件
	const customMiddlewares = [thunk, reduxPromise];
	// 使用 prepend 方法将自定义中间件添加到默认中间件之前
	// @ts-ignore
	const defaultMiddlewares = getDefaultMiddleware({ serializableCheck: false });
	const finalMiddlewares = defaultMiddlewares.prepend(...customMiddlewares);
	return finalMiddlewares;
};
// store
export const store = configureStore({
	reducer: persistReducerConfig,
	middleware: customMiddleware,
	devTools: false
});

// create persist store
export const persistor = persistStore(store);

export type RootState = ReturnType<typeof store.getState>;
export type AppDispatch = typeof store.dispatch;
export const useSelector: TypedUseSelectorHook<RootState> = useReduxSelector;
export const useDispatch = () => useReduxDispatch<AppDispatch>();
